package com.gtworldmobile.activities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.gtworldmobile.classes.Uploader;
import com.gtworldmobile.dialogs.EventoDialog;
import com.gtworldmobile.entity.AsistenciaEvento;
import com.gtworldmobile.entity.Evento;
import com.gtworldmobile.entity.Poi;
import com.gtworldmobile.json.JSONParser;
import org.mixare.R;

public class InformacionPoiActivity extends TabActivity {
	
	private String URL_VISITA= "";
	private String VISITA_SERVICES="GTWorld/services/com.gtworld.entity.visitapoi/";
	private String URL_COMENTAR="";
	private String COMENTAR_SERVICES="GTWorld/services/com.gtworld.entity.asistenciaevento/";
	private String NOMBRE_PREF="preferencias";
	
	public String ip_cargada= "";
	
	private static final int COMENT_DIALOG = 0;
	
	private static final int EVENTO = 0;
	private static final int EDITAR_EVENTO = 2;
	private static final int POI = 3;
	
	private List<Evento> listEvento=null;
	private Evento selectedEvento=null;
	private Poi poi;
	private boolean alreadyExistEvento;
	private String idPoi = "";
	/*
	EditText comentarioVisita;
	ListView l;
	EditText nombrePoi;
	EditText descripcionPoi;	
	EditText urlPoi;
	*/
	private String comentarioEvento="";
	private String comentarioVisit="";
	
	private Activity infoPoiCtx;
	private ProgressDialog progress;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.informacion_poi);
        
        SharedPreferences prefs = getSharedPreferences("preferencias",Context.MODE_PRIVATE);
		ip_cargada= prefs.getString("ip", "");
        
        URL_VISITA=ip_cargada.concat(VISITA_SERVICES);
        URL_COMENTAR= ip_cargada.concat(COMENTAR_SERVICES);
      
        
        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
        	idPoi = extras.getString("idPoi");
        }
        infoPoiCtx=this;
        setUI();
        /*
        l = (ListView) findViewById(R.id.listview_eventos_poi);
        comentarioVisita = (EditText) findViewById(R.id.comentarioVisita);
        nombrePoi = (EditText) findViewById(R.id.nombre_poi);
    	descripcionPoi = (EditText) findViewById(R.id.descripcion_info_poi);
    	urlPoi = (EditText) findViewById(R.id.url_poi);
    	*/
    	new RecibirInfoPoi().execute();
        /*
        JSONParser jsonEventos = new JSONParser(this,URL_EVENTO+idPoi,EVENTO);
        JSONParser jsonPoi = new JSONParser(this,URL_POI+idPoi,POI);

		try {
			jsonEventos.readAndParseJSON();
			while(jsonEventos.thread.isAlive());
			listEvento = jsonEventos.getListEvento();
			jsonPoi.readAndParseJSON();
			while(jsonPoi.thread.isAlive());
			poi = jsonPoi.getPoi();
			if(poi!=null){
				nombrePoi.setText(poi.getNombrePoi());
				descripcionPoi.setText(poi.getDescripcionPoi());
				urlPoi.setText(poi.getUrlWebPoi());
			}
		} catch (JSONException e) {
			Toast.makeText(InformacionPoiActivity.this,e.getMessage(),
	                Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
        

		l.setAdapter(new miAdapter(this,listEvento));
		l.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent,View view,int position,long id){

				selectedEvento=listEvento.get(position);				
				startEventoDialog();
				
			}
		}); */
   
    }
    
    private void setUI(){
    	TabSpec spec = getTabHost().newTabSpec("poi");
    	Resources res = getResources();

    	spec.setContent(R.id.info_poi);
    	spec.setIndicator("POI",res.getDrawable(android.R.drawable.ic_dialog_info));
    	getTabHost().addTab(spec);
    	
    	spec = getTabHost().newTabSpec("eventopoi");
    	spec.setContent(R.id.informacion_evento_poi);
    	spec.setIndicator("EVENTO",res.getDrawable(android.R.drawable.ic_dialog_dialer));
    	getTabHost().addTab(spec);
    	
    	getTabHost().setCurrentTab(0);

    }
    
    private static class miAdapter extends BaseAdapter {
    	 
		private LayoutInflater mInflater;
		List<Evento> listEvento=null;
		Context ctx;
 
		public miAdapter(Context context,List<Evento> listEvento) {
			
			ctx = context;
			mInflater = LayoutInflater.from(context);
			this.listEvento=listEvento;
 
		}
 
		public View getView(int position, View convertView, ViewGroup parent) {
 
 
			TextView nombreEventoPoi;
			TextView ponenteEvento;
			TextView localEvento;
			TextView horaEvento;
 
			ImageView imagenEvento;
 
 
			if (convertView == null) {
 
				convertView = mInflater.inflate(R.layout.fila_listview, null);
 
			} 
 
			nombreEventoPoi = (TextView) convertView.findViewById(R.id.nombre_evento_poi);
			ponenteEvento = (TextView) convertView.findViewById(R.id.ponente_evento);
			localEvento = (TextView) convertView.findViewById(R.id.local_evento);
			horaEvento = (TextView) convertView.findViewById(R.id.hora_evento);
			
			imagenEvento = (ImageView) convertView.findViewById(R.id.image_evento_poi);
 
			Evento event=listEvento.get(position);
			
			Calendar calendar = Calendar.getInstance();
			DateFormat formatter = new SimpleDateFormat("hh:mm");
	        calendar.setTimeInMillis(event.getFechaEvento().getTime());
			
			nombreEventoPoi.setText(event.getNombreEvento());
			ponenteEvento.setText(event.getPonenteEvento());
			localEvento.setText(event.getLocalEvento());
			horaEvento.setText(formatter.format(calendar.getTime()).toString());
			
			if(event.getEsPonenciaEvento()==true)
				imagenEvento.setImageResource(R.drawable.presentation);
			else
				imagenEvento.setImageResource(R.drawable.taller);
			
			return convertView;

 
		}
 
 
		public int getCount() {
			return listEvento.size();
 
		}
 
 
		public Object getItem(int position) {
 
			return position;
 
		}
 
 
		public long getItemId(int position) {
 
			return position;
 
		}
	}
    
    private void startEventoDialog() {
    	new CargarComent().execute();
    }
    
    public void toGallery(View v){
    	try{
    		Class<?> clase=Class.forName("com.gtworldmobile.activities.GalleryPoiActivity");
    		Intent inte = new Intent(InformacionPoiActivity.this,clase);
    		inte.putExtra("idPoi", idPoi);
    		this.startActivity(inte);
    	}catch(ClassNotFoundException e){
    		e.printStackTrace();
    	}
    }
    
    public void registrarVisita(View v){
    		EditText comentarioVisita=(EditText) findViewById(R.id.comentarioVisita);	
			comentarioVisit = comentarioVisita.getText().toString();
    		new RegistrarVisita().execute();
	
    }
    
    	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	switch(requestCode) {
    		case (COMENT_DIALOG) : {
    			
    			if (resultCode == Activity.RESULT_OK) {    				
    				comentarioEvento = data.getStringExtra(EventoDialog.COMENTARIO_RESULT);
    				new EviarComent().execute();
    				/*String comentario = data.getStringExtra(EventoDialog.COMENTARIO_RESULT);
    				
    				HttpClient httpClient = new DefaultHttpClient();
    				
    				JSONObject dato = new JSONObject();
    				SharedPreferences prefs = getSharedPreferences(NOMBRE_PREF, MODE_PRIVATE);
 
    				try {
    					
    					String jsonEntity="{\"asistenciaEventoPK\":";
						dato.put("idUsuario", prefs.getString(NOMBRE_PREF, "admin"));
	    				dato.put("idEvento", Integer.parseInt(selectedEvento.getId()));
	    				dato.put("idPoi", idPoi);
	    				
	    				jsonEntity=jsonEntity+dato.toString()+",";
	    				jsonEntity=jsonEntity+"\"fechaAsistenciaEvento\":"+Long.parseLong(selectedEvento.getFecha())+",";
	    				jsonEntity=jsonEntity+"\"comentarioAsistenciaEvento\":\""+comentario+"\"}";

	    				HttpResponse resp;
	    				StringEntity entity;	    				
						entity = new StringEntity(jsonEntity);
						
						
						if(!alreadyExistEvento){ 
							
			    				HttpPost post = new HttpPost(URL_COMENTAR);
								post.setEntity(entity);
								post.setHeader("content-type", "application/json");						
								resp = httpClient.execute(post);
								
								if(resp.getStatusLine().toString().contains("204")){
									Toast.makeText(InformacionPoiActivity.this,"Comentario guardado",
				    		                Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(InformacionPoiActivity.this,"No se pudo enviar comentario",
				    		                Toast.LENGTH_LONG).show();
								}
								
						}else{	
							
								HttpPut put = new HttpPut(URL_COMENTAR);
								put.setHeader("content-type", "application/json");
								put.setEntity(entity);
								resp = httpClient.execute(put);
								
								if(resp.getStatusLine().toString().contains("204")){
									Toast.makeText(InformacionPoiActivity.this,"Comentario actualizado",
				    		                Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(InformacionPoiActivity.this,"No se pudo enviar comentario",
				    		                Toast.LENGTH_LONG).show();
								}
	
						}	
	
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						Toast.makeText(InformacionPoiActivity.this,e.getMessage(),
	    		                Toast.LENGTH_LONG).show();
					} catch (JSONException e) {
						e.printStackTrace();
						Toast.makeText(InformacionPoiActivity.this,e.getMessage(),
	    		                Toast.LENGTH_LONG).show();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
						Toast.makeText(InformacionPoiActivity.this,e.getMessage(),
	    		                Toast.LENGTH_LONG).show();
					} catch (IOException e) {						
						e.printStackTrace();
						Toast.makeText(InformacionPoiActivity.this,e.getMessage(),
	    		                Toast.LENGTH_LONG).show();
					}
					*/
    			}
    		break;
    		}
    	}
    }
    
    public class EviarComent extends AsyncTask<Void, Void, Void> {
    	List<String> estatus=new ArrayList<String>();
		protected void onPreExecute() {

			progress = ProgressDialog.show(infoPoiCtx, "Enviando comentario...",
					"Por favor espere", true);

		}

		protected void onPostExecute(Void p) {			
			progress.dismiss();
			for(String msj:estatus){
				Toast.makeText(InformacionPoiActivity.this,
						msj, Toast.LENGTH_LONG).show();
			}

		}

		@Override
		protected Void doInBackground(Void... params) {
			
			try {

				HttpClient httpClient = new DefaultHttpClient();
				
				JSONObject dato = new JSONObject();
				SharedPreferences prefs = getSharedPreferences(NOMBRE_PREF, MODE_PRIVATE);

				try {
					
					String jsonEntity="{\"asistenciaEventoPK\":";
					dato.put("idUsuario", prefs.getString("id", ""));
    				dato.put("idEvento", selectedEvento.getIdEvento());
    				dato.put("idPoi", idPoi);
    				
    				jsonEntity=jsonEntity+dato.toString()+",";
    				jsonEntity=jsonEntity+"\"fechaAsistenciaEvento\":"+ selectedEvento.getFechaEvento().getTime()+",";
    				jsonEntity=jsonEntity+"\"comentarioAsistenciaEvento\":\""+comentarioEvento+"\"}";

    				HttpResponse resp;
    				StringEntity entity;	    				
					entity = new StringEntity(jsonEntity);
					
					
					if(!alreadyExistEvento){ 
						
		    				HttpPost post = new HttpPost(URL_COMENTAR);
							post.setEntity(entity);
							post.setHeader("content-type", "application/json");						
							resp = httpClient.execute(post);
							
							if(resp.getStatusLine().toString().contains("204")){
								estatus.add("Comentario guardado");
							}else{
								estatus.add("No se pudo enviar comentario");
							}
							
							
					}else{	
						
							HttpPut put = new HttpPut(URL_COMENTAR);
							put.setHeader("content-type", "application/json");
							put.setEntity(entity);
							resp = httpClient.execute(put);
							
							if(resp.getStatusLine().toString().contains("204")){
								estatus.add("Comentario actualizado");
							}else{
								estatus.add("No se pudo enviar comentario");
							}
							

					}	

				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					estatus.add(e.getMessage());
				} catch (JSONException e) {
					e.printStackTrace();
					estatus.add(e.getMessage());
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					estatus.add(e.getMessage());
				} catch (IOException e) {						
					e.printStackTrace();
					estatus.add(e.getMessage());
				}
				
			}catch (Exception e) {
				estatus.add(e.getMessage());
					e.printStackTrace();
			}
			return null;
		}

	}
    
    public class RegistrarVisita extends AsyncTask<Void, Void, Void> {
    	List<String> estatus=new ArrayList<String>();
		protected void onPreExecute() {

			progress = ProgressDialog.show(infoPoiCtx, "Guardando visita...",
					"Por favor espere...", true);

		}

		protected void onPostExecute(Void p) {
			
			progress.dismiss();
			
			
			for(String msj:estatus){
				Toast.makeText(InformacionPoiActivity.this,
						msj, Toast.LENGTH_LONG).show();
			}

	
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			
			HttpClient httpClient = new DefaultHttpClient();
			Calendar DateTime = Calendar.getInstance();
			
			JSONObject dato = new JSONObject();
			SharedPreferences prefs = getSharedPreferences(NOMBRE_PREF, MODE_PRIVATE);			

			try {
				
				String jsonEntity="{\"visitaPoiPK\":";
				dato.put("idUsuario", prefs.getString("id", ""));
				dato.put("idPoi", idPoi);
				dato.put("fechaVisitaPoi", DateTime.getTimeInMillis());

				jsonEntity=jsonEntity+dato.toString()+",";				
				jsonEntity=jsonEntity+"\"comentarioVisitaPoi\":\""+comentarioVisit+"\"}";
				System.out.println(jsonEntity);
				HttpResponse resp;
				StringEntity entity;	    				
				entity = new StringEntity(jsonEntity);

	    		HttpPost post = new HttpPost(URL_VISITA);
				post.setEntity(entity);
				post.setHeader("content-type", "application/json");						
				resp = httpClient.execute(post);
				
				if(resp.getStatusLine().toString().contains("204")){
					estatus.add("Comentario guardado");
				}else{
					estatus.add("No se pudo enviar comentario");
				}
	
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				estatus.add(e.getMessage());
			} catch (JSONException e) {
				e.printStackTrace();
				estatus.add(e.getMessage());
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				estatus.add(e.getMessage());
			} catch (IOException e) {						
				e.printStackTrace();
				estatus.add(e.getMessage());
			}
			
			return null;
		}

	}
    
    public class CargarComent extends AsyncTask<Void, Void, Void> {
    	List<String> estatus=new ArrayList<String>();
    	String coment="";
		protected void onPreExecute() {

			progress = ProgressDialog.show(infoPoiCtx, "...",
					"Por favor espere...", true);

		}

		protected void onPostExecute(Void p) {
			
			progress.dismiss();
			
			for(String msj:estatus){
				Toast.makeText(InformacionPoiActivity.this,
						msj, Toast.LENGTH_LONG).show();
			}
			
	    	Intent intent = new Intent(InformacionPoiActivity.this,EventoDialog.class);
	    	intent.putExtra("coment", coment);
	    	startActivityForResult(intent, COMENT_DIALOG);
	
		}

		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences prefs = getSharedPreferences(NOMBRE_PREF, MODE_PRIVATE);	    	
	    	String parametros=idPoi+"/"+prefs.getString("id", "")+"/"+selectedEvento.getIdEvento();
	    	JSONParser jsonEdit = new JSONParser(InformacionPoiActivity.this,parametros,EDITAR_EVENTO);
	    	
	    	try {
				jsonEdit.readAndParseJSON();			
				while(jsonEdit.thread.isAlive());
				coment = jsonEdit.getComentEvento();
				alreadyExistEvento = jsonEdit.alredyExistAsistencia();				
			} catch (JSONException e) {
				estatus.add(e.getMessage());
				e.printStackTrace();
			}

	    	if(!alreadyExistEvento)
	    		coment="";
			
			return null;
		}

	}
    
    public class RecibirInfoPoi extends AsyncTask<Void, Void, Void> {
    	List<String> estatus=new ArrayList<String>();
    	
		protected void onPreExecute() {

			progress = ProgressDialog.show(infoPoiCtx, "Recibiendo datos de Poi",
					"Por favor espere...", true);

		}

		protected void onPostExecute(Void p) {
			progress.dismiss();
			
			ListView l = (ListView) findViewById(R.id.listview_eventos_poi);
			EditText  nombrePoi = (EditText) findViewById(R.id.nombre_poi);
			EditText descripcionPoi = (EditText) findViewById(R.id.descripcion_info_poi);	
			EditText urlPoi = (EditText) findViewById(R.id.url_poi);
			
			if(poi!=null){
				nombrePoi.setText(poi.getNombrePoi());
				descripcionPoi.setText(poi.getDescripcionPoi());
				urlPoi.setText(poi.getUrlWebPoi());
			}
			
			l.setAdapter(new miAdapter(InformacionPoiActivity.this,listEvento));
			l.setOnItemClickListener(new OnItemClickListener(){
				public void onItemClick(AdapterView<?> parent,View view,int position,long id){

					selectedEvento=listEvento.get(position);				
					startEventoDialog();
					
				}
			});
			
			
			
			for(String msj:estatus){
				Toast.makeText(InformacionPoiActivity.this,
						msj, Toast.LENGTH_LONG).show();
			}

		}

		@Override
		protected Void doInBackground(Void... params) {

			JSONParser jsonEventos = new JSONParser(InformacionPoiActivity.this,idPoi,EVENTO);
	        JSONParser jsonPoi = new JSONParser(InformacionPoiActivity.this,idPoi,POI);

			try {
				jsonPoi.readAndParseJSON();
				while(jsonPoi.thread.isAlive());
				poi = jsonPoi.getPoi();
				jsonEventos.readAndParseJSON();
				estatus.add(jsonPoi.estatus);
				while(jsonEventos.thread.isAlive());
				listEvento = jsonEventos.getListEvento();				
				estatus.add(jsonEventos.estatus);
				
			} catch (JSONException e) {
				estatus.add(e.getMessage());
				e.printStackTrace();
			}
			
			return null;
		}

	}
    
}